<template>
  <div class="useList">
    <div class="record--filter--box">
      <a-input-search
        class="useList--inp"
        placeholder="输入姓名/账号"
        @search="onSearch"
        v-model="searchName"
        v-preventReClick
      />
      <span
        class="span--left"
        v-if="userInfo.level === 5 || userInfo.level === 1"
        >选择角色：</span
      >
      <a-select
        default-value="all"
        @change="handleRoleChange"
        :options="RoleOptions"
        class="record--modeSelect"
        v-if="userInfo.level === 5 || userInfo.level === 1"
      >
      </a-select>
    </div>
    <div class="user-table">
      <a-table
        :columns="columns"
        :data-source="userList"
        :row-key="(record) => record.id"
        :pagination="false"
        :loading="loading"
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
        }"
        :customRow="customRow"
        :rowClassName="
          () => {
            return 'user-table';
          }
        "
        :locale="{ emptyText: '暂无数据' }"
      >
        <div
          slot="filterDropdown"
          slot-scope="{
            setSelectedKeys,
            selectedKeys,
            confirm,
            clearFilters,
            column,
          }"
          style="padding: 8px"
        >
          <a-input
            v-ant-ref="(c) => (searchInput = c)"
            :placeholder="`输入查询的${column.title}`"
            :value="selectedKeys[0]"
            style="width: 188px; margin-bottom: 8px; display: block"
            @change="
              (e) => setSelectedKeys(e.target.value ? [e.target.value] : [])
            "
            @pressEnter="
              () => handleSearch(selectedKeys, confirm, column.dataIndex)
            "
          />
          <a-button
            type="primary"
            icon="search"
            size="small"
            style="width: 90px; margin-right: 8px"
            @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
          >
            查询
          </a-button>
          <a-button
            size="small"
            style="width: 90px"
            @click="() => handleReset(clearFilters)"
          >
            重置
          </a-button>
        </div>
        <a-icon
          slot="filterIcon"
          slot-scope="filtered"
          type="search"
          :style="{ color: filtered ? '#108ee9' : undefined }"
        />
        <span slot="level" slot-scope="level" class="record--span">
          {{ job[level] }}
        </span>
      </a-table>
    </div>
    <div class="pagination--box">
      <a-config-provider :locale="locale">
        <a-pagination
          v-model="current"
          :page-size-options="pageSizeOptions"
          :total="total"
          show-size-changer
          :page-size="pageSize"
          @showSizeChange="onShowSizeChange"
          @change="handleTableChange"
        >
          <template slot="buildOptionText" slot-scope="props">
            <span v-if="props.value !== '50'">{{ props.value }}条/页</span>
          </template>
        </a-pagination>
      </a-config-provider>
    </div>
    <div class="user--btn">
      <a-space size="large">
        <button
          :class="['btn', { dis: userInfo.level === 5 }]"
          @click="handleAddUser"
          :disabled="userInfo.level === 5"
        >
          添加用户
        </button>
        <a-popconfirm
          title="确定要删除么?"
          ok-text="确定"
          cancel-text="取消"
          @confirm="confirmDelete"
          :disabled="userInfo.level === 5 || !selectUser"
        >
          <button
            :class="[
              'btn delete',
              { dis: userInfo.level === 5 || !selectUser, delete: selectUser },
            ]"
          >
            删除用户
          </button>
        </a-popconfirm>
        <button
          :class="['btn', { dis: userInfo.level === 5 || !selectUser }]"
          :disabled="userInfo.level === 5 || !selectUser"
          @click="edit"
        >
          编辑用户
        </button>
        <a-popconfirm
          title="确定要重置这个账号的密码?"
          ok-text="确定"
          cancel-text="取消"
          @confirm="resetPsw"
          :disabled="userInfo.level === 5 || !selectUser"
        >
          <button
            :class="['btn', { dis: userInfo.level === 5 || !selectUser }]"
          >
            重置密码
          </button>
        </a-popconfirm>
      </a-space>
    </div>
    <ModalSlot
      :visible="userModalVisible"
      :title="isAdd ? '添加用户' : '编辑用户'"
      @handleCancel="userModalVisible = false"
      :bodyStyle="{ padding: '10px' }"
    >
      <a-form
        :form="form1"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 12 }"
      >
        <a-form-item label="姓名">
          <a-input
            :maxLength="30"
            autoComplete="off"
            v-decorator="[
              'name',
              {
                rules: [
                  { required: true, message: '请输入姓名!' },
                  {
                    pattern: /^[a-zA-Z0-9\u4e00-\u9fa5!]+$/,
                    message: '姓名格式不正确,使用英文、中文、数字或组合!',
                  },
                ],
              },
            ]"
          />
        </a-form-item>
        <a-form-item label="账号">
          <a-input
            :maxLength="10"
            autoComplete="off"
            v-decorator="[
              'user',
              {
                rules: [
                  { required: true, message: '请输入账号!' },
                  {
                    pattern: /^[0-9a-zA-Z]*$/,
                    message: '账号格式不正确,使用英文、数字或组合!',
                  },
                ],
              },
            ]"
          />
        </a-form-item>

        <!-- <a-form-item label="密码">
          <a-input-password
            v-decorator="[
              'passwd',
              {
                rules: [
                  { required: true, message: '请输入密码!' },
                  {
                    pattern: /^\S+$/,
                    message: '密码中不能带有空格!',
                  },
                ],
                initialValue: '123456',
              },
            ]"
          />
        </a-form-item> -->

        <a-form-item label="电话">
          <a-input
            :maxLength="30"
            autoComplete="off"
            v-decorator="[
              'tel',
              {
                rules: [
                  {
                    pattern: /^1[3,4,5,6,7,8,9][0-9]{9}$/,
                    message: '请输入正确的手机号',
                  },
                ],
              },
            ]"
          />
        </a-form-item>

        <a-form-item label="邮箱">
          <a-input
            :maxLength="30"
            autoComplete="off"
            v-decorator="[
              'email',
              {
                rules: [
                  {
                    pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
                    message: '请输入正确的邮箱',
                  },
                ],
              },
            ]"
          />
        </a-form-item>

        <!-- <a-form-item label="关联患者端SN">
          <a-input autoComplete="off" v-decorator="['patient_sn']" />
        </a-form-item>

        <a-form-item label="关联专家端SN">
          <a-input autoComplete="off" v-decorator="['doctor_sn']" />
        </a-form-item> -->

        <a-form-item label="自动选图">
          <a-switch
            v-decorator="['intelligent', { valuePropName: 'checked' }]"
          />
        </a-form-item>

        <a-form-item label="角色">
          <a-radio-group
            @change="levelChange"
            :options="options"
            v-decorator="[
              'level',
              {
                rules: [{ required: true, message: '请选择角色!' }],
                initialValue: 7,
              },
            ]"
          />
        </a-form-item>

        <a-form-item label="电子签名">
          <MyUpload
            :sign="sign"
            @on-change="handleSignChange"
            :imgServerUrl="imgServerUrl"
            :userId="userId"
          />
        </a-form-item>

        <a-form-item :wrapper-col="{ span: 12, offset: 7 }">
          <a-space size="large">
            <button class="modal-btn cancal" @click="userCancel">取消</button>
            <button @click="userSubmit" class="modal-btn">确定</button>
          </a-space>
        </a-form-item>
      </a-form>
    </ModalSlot>
  </div>
</template>

<script>
import ModalSlot from "@/components/ModalSlot";
import {
  getUserList,
  addUser,
  delUser,
  updateUser,
  bulkDelUser,
} from "@/api/login";
import MyUpload from "@/components/MyUpload";
import { encrypt, decrypt } from "@/utils/cryptoTools";
import zhCN from "ant-design-vue/lib/locale-provider/zh_CN";
import { mapState } from "vuex";
import { v4 as uuidv4 } from "uuid";
import { addLogInfo } from "@/api/logInfo";
import { addUserToImpl } from "@/api/assess"
export default {
  name: "UserlistComp",

  data() {
    return {
      columns: [
        {
          title: "姓名",
          dataIndex: "name",
          key: "name",
          ellipsis: true,
          width: 200,
          scopedSlots: {
            filterDropdown: "filterDropdown",
            filterIcon: "filterIcon",
            customRender: "customRender",
          },
          onFilter: (value, record) =>
            record.name.toString().toLowerCase().includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: (visible) => {
            if (visible) {
              setTimeout(() => {
                this.searchInput.focus();
              }, 0);
            }
          },
        },
        {
          title: "角色",
          dataIndex: "level",
          key: "level",
          scopedSlots: { customRender: "level" },
        },
        {
          title: "账号",
          dataIndex: "user",
          key: "user",
          ellipsis: true,
          width: 200,
        },
        // {
        //   title: "密码",
        //   dataIndex: "passwd",
        //   key: "passwd",
        // },
        {
          title: "电话",
          dataIndex: "tel",
          key: "tel",
        },
        {
          title: "邮箱",
          dataIndex: "email",
          key: "email",
          ellipsis: true,
          width: 250,
        },
        // {
        //   title: "操作",
        //   key: "action",
        //   scopedSlots: { customRender: "action" },
        // },
      ],
      isAdd: true, //添加or编辑
      userList: [],
      loading: false,
      userModalVisible: false,
      form1: this.$form.createForm(this, { name: "user" }),
      pageSizeOptions: ["10", "20", "30"],
      total: 0,
      current: 1,
      pageSize: 10,
      level: 7, //角色
      searchText: "",
      searchInput: null,
      searchedColumn: "",
      userObj: {
        id: "",
        name: "",
        user: "",
        passwd: "",
        tel: "",
        email: "",
        level: 1,
        sign: "",
      },
      sign: "",
      selectedRowKeys: [],
      selectUser: "",
      job: {
        7: "医生",
        6: "专家",
        8: "CRC"
      },
      locale: zhCN,
      RoleOptions: [
        {
          value: "all",
          label: "所有",
        },
        {
          value: 7,
          label: "医生",
        },
        {
          value: 6,
          label: "专家",
        },
      ],
      searchLevel: null,
      searchName: "",
      userId: "",
    };
  },
  components: {
    ModalSlot,
    MyUpload,
  },
  computed: {
    ...mapState(["userInfo", "SERVERBASE_URL", "imgServerUrl","RECORD_URL"]),
    options() {
      if (this.userInfo.level === 1) {
        return [
          { label: "医生", value: 7 },
          { label: "专家", value: 6 },
          { label: "CRC", value: 8 },
        ];
      } else if (this.userInfo.level === 2) {
        return [{ label: "医生", value: 7 }];
      } else {
        return [
          { label: "医生", value: 7 },
          { label: "专家", value: 6 },
        ];
      }
    },
  },
  mounted() {
    this.getUser();
  },

  methods: {
    //获取用户
    getUser() {
      const vm = this;
      vm.loading = true;
      console.log("登录的userInfo", this.userInfo);
      let params = {
        total: this.total,
        current: this.current,
        pageSize: this.pageSize,
        name: this.searchText,
        level: this.userInfo.level,
        searchLevel: this.searchLevel,
      };
      getUserList(this.SERVERBASE_URL, params)
        .then((res) => {
          if (res.code == 200) {
            vm.userList = res.data.rows;
            vm.total = res.data.count;
            vm.loading = false;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //选择某个用户
    onSelectChange(selectedRowKeys, record) {
      console.log("selectedRowKeys changed: ", selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
      this.selectUser = record.pop();
      console.log("selectUser", this.selectUser);
    },

    //table pagination 改变回调
    handleTableChange(pagination) {
      this.current = pagination;
      this.getUser();
    },
    //pageSize 变化的回调
    onShowSizeChange(current, pageSize) {
      console.log(current, pageSize);
      this.pageSize = pageSize;
      this.current = 1;
      this.getUser();
    },
    //新增用户
    handleAddUser() {
      this.userModalVisible = true;
      this.isAdd = true;
      this.form1.resetFields();
      this.sign = "";
      this.userId = uuidv4();
    },
    //用户确认修改
    userSubmit(e) {
      e.preventDefault();
      const vm = this;
      this.form1.validateFields((err, values) => {
        if (!err) {
          console.log("Received values of form: ", values);
          const allow_sn = {};
          if (values.patient_sn) {
            if (values.patient_sn.includes(",")) {
              allow_sn.patient_sn = values.patient_sn.split(",");
            } else {
              allow_sn.patient_sn = values.patient_sn;
            }
          } else {
            allow_sn.patient_sn = this.userInfo.allow_sn.patient_sn;
          }
          if (values.doctor_sn) {
            if (values.doctor_sn.includes(",")) {
              allow_sn.doctor_sn = values.doctor_sn.split(",");
            } else {
              allow_sn.doctor_sn = values.doctor_sn;
            }
          } else {
            allow_sn.doctor_sn = this.userInfo.allow_sn.doctor_sn;
          }
          delete values.doctor_sn;
          delete values.patient_sn;
          //是新增
          if (vm.isAdd) {
            const addUserInfo = {
              ...values,
              level: vm.level,
              sign: vm.sign,
              passwd: encrypt("Cobot_123"),
              allow_sn: JSON.stringify(allow_sn),
              id: vm.userId,
              intelligent: values.intelligent ? 1 : 0,
            };
            addUser(this.SERVERBASE_URL, addUserInfo)
              .then((res) => {
                if (res.code == 200) {
                  vm.$message.success("成功！");
                  addLogInfo(vm.SERVERBASE_URL, {
                    name: vm.userInfo.name,
                    type: "用户",
                    event: "新增用户",
                  });
                  vm.userModalVisible = false;
                  vm.form1.resetFields();
                  vm.sign = "";
                  vm.getUser();
                  if(addUserInfo.level == 6){
                    addUserToImpl(vm.RECORD_URL,{name:addUserInfo.name,level:addUserInfo.level,blind:1})
                  }
                } else {
                  console.log("res: ", res);
                  if (res.err) {
                    vm.$message.error(`${res.err}`);
                  } else {
                    vm.$message.error(`账户已存在!`);
                  }
                }
              })
              .catch((err) => {
                console.log("err: ", err);
              });
          } else {
            //是编辑
            let editUserInfo = {
              ...values,
              sign: vm.sign,
              allow_sn: JSON.stringify(allow_sn),
              intelligent: values.intelligent ? 1 : 0,
            };
            delete editUserInfo.patient_sn;
            delete editUserInfo.doctor_sn;
            updateUser(this.SERVERBASE_URL, vm.userObj.id, editUserInfo)
              .then((res) => {
                if (res.code == 200) {
                  vm.$message.success("编辑成功！");
                  vm.userModalVisible = false;
                  vm.form1.resetFields();
                  vm.getUser();
                  vm.selectUser = {
                    ...vm.selectUser,
                    ...res.data,
                  };
                  vm.sign = "";
                } else {
                  console.log("res: ", res);
                  if (res.err) {
                    vm.$message.error(`${res.err}`);
                  } else {
                    vm.$message.error(`账户已存在!`);
                  }
                }
              })
              .catch((err) => {
                console.log("err: ", err);
              });
          }
        }
      });
    },
    //用户取消
    userCancel(e) {
      e.preventDefault();
      this.userModalVisible = false;
      this.form1.resetFields();
      this.sign = "";
    },

    //查询
    handleSearch(selectedKeys, confirm, dataIndex) {
      //   confirm();
      this.searchText = selectedKeys[0];
      this.searchedColumn = dataIndex;
      this.current = 1;
      this.getUser();
    },

    //查询重置
    handleReset(clearFilters) {
      clearFilters();
      this.searchText = "";
      this.current = 1;
      this.getUser();
    },
    //编辑
    edit() {
      if (!this.selectUser) {
        this.$message.warning("请选择用户！");
        return;
      }
      if (this.selectUser.level === 2 && this.userInfo.level === 2) {
        if (this.selectUser.id != this.userInfo.id)
          this.$message.warning("管理员不能编辑其他管理员信息！");
        return;
      }
      let obj = Object.assign({}, this.selectUser);
      let allow_sn = obj.allow_sn ? JSON.parse(obj.allow_sn) : "";
      if (allow_sn) {
        if (Array.isArray(allow_sn.patient_sn)) {
          obj.patient_sn = allow_sn.patient_sn.join(",");
        } else {
          obj.patient_sn = allow_sn.patient_sn;
        }
        if (Array.isArray(allow_sn.doctor_sn)) {
          obj.doctor_sn = allow_sn.doctor_sn.join(",");
        } else {
          obj.doctor_sn = allow_sn.doctor_sn;
        }
      }
      delete obj.createdAt;
      delete obj.deletedAt;
      delete obj.updatedAt;
      delete obj.id;
      delete obj.sign_url;
      delete obj.allow_sn;
      this.isAdd = false;
      this.userModalVisible = true;
      this.userObj = this.selectUser;
      this.userId = this.selectUser.id;
      obj.passwd = decrypt(obj.passwd);
      obj.intelligent = obj.intelligent ? true : false;
      this.sign = obj.sign;
      delete obj.sign;
      delete obj.passwd;
      console.log("编辑回填信息", obj);
      this.$nextTick(() => {
        this.form1.setFieldsValue(obj);
      });
    },
    //删除用户操作
    confirmDelete() {
      if (this.selectedRowKeys.length === 0) {
        this.$message.warning("请选择用户！");
        return;
      }
      if (this.userInfo.level === 2) {
        if (this.selectUser.level == 2) {
          this.$message.warning("管理员不能删除管理员账号！");
          return;
        }
        this.confirmDeleteCb();
      } else if (this.userInfo.level == 1) {
        console.log("this.userInfo", this.userInfo);
        this.confirmDeleteCb();
      } else {
        console.log("this.userInfo", this.userInfo);
        this.confirmDeleteCb();
      }
    },
    //删除用户回调
    async confirmDeleteCb() {
      const vm = this;
      if (this.selectedRowKeys.length === 1) {
        const user_id = this.selectedRowKeys[0];
        try {
          const res = await delUser(this.SERVERBASE_URL, user_id);
          if (res.code == 200) {
            vm.$message.success("删除成功！");
            addLogInfo(vm.SERVERBASE_URL, {
              name: vm.userInfo.name,
              type: "用户",
              event: "删除用户",
            });
            if (vm.selectedRowKeys.length === vm.userList.length) {
              vm.current = 1;
            }
            vm.selectedRowKeys = [];
            vm.selectUser = "";
            vm.getUser();
          }
        } catch (err) {
          console.log(err);
        }
      } else if (this.selectedRowKeys.length > 1) {
        try {
          const res = await bulkDelUser(
            this.SERVERBASE_URL,
            this.selectedRowKeys
          );
          if (res.code == 200) {
            vm.$message.success("删除成功！");
            addLogInfo(vm.SERVERBASE_URL, {
              name: vm.userInfo.name,
              type: "用户",
              event: "批量删除用户",
            });
            console.log("selectedRowKeys", vm.selectedRowKeys);
            console.log("userList", vm.userList);
            if (
              vm.selectedRowKeys.length === vm.userList.length ||
              vm.selectedRowKeys.length > vm.userList.length
            ) {
              vm.current = 1;
            }
            vm.selectedRowKeys = [];
            vm.selectUser = "";
            vm.getUser();
          }
        } catch (err) {
          console.log(err);
        }
      }
    },
    //重置密码操作
    resetPsw() {
      if (!this.selectUser) {
        this.$message.warning("请选择用户！");
        return;
      }
      if (this.userInfo.level === 5) {
        if (this.selectUser.level != 1) {
          this.$message.warning("工程师只能重置超级管理员的密码！");
          return;
        }
        this.resetPswCb("Cobot_123");
      } else if (this.userInfo.level == 1) {
        this.resetPswCb("Cobot_123");
      } else if (this.userInfo.level == 2) {
        if (this.selectUser.level == 2) {
          this.$message.warning("管理员不能重置管理员密码！");
          return;
        }
        this.resetPswCb("Cobot_123");
      } else {
        console.log("this.userInfo", this.userInfo);
      }
    },
    //重置密码回调
    resetPswCb(passwd) {
      console.log(
        "%c [ passwd ]-594",
        "font-size:13px; background:pink; color:#bf2c9f;",
        passwd
      );
      const vm = this;
      updateUser(this.SERVERBASE_URL, this.selectUser.id, {
        passwd: encrypt(passwd),
      })
        .then((res) => {
          if (res.code == 200) {
            vm.$message.success("重置密码成功！");
            vm.getUser();
            vm.selectUser = {
              ...vm.selectUser,
              ...res.data,
            };
          } else {
            console.log("res: ", res);
          }
        })
        .catch((err) => {
          console.log("err: ", err);
        });
    },
    handleSignChange(sign) {
      this.sign = sign;
    },
    levelChange(e) {
      this.level = e.target.value;
    },
    customRow(record) {
      return {
        on: {
          click: () => {
            if (this.selectUser) {
              if (this.selectUser.id != record.id) {
                let keys = [];
                keys.push(record.id);
                this.selectedRowKeys = keys;
                this.selectUser = record;
                console.log("this.selectUser", this.selectUser);
              } else {
                this.selectedRowKeys = [];
                this.selectUser = "";
              }
            } else {
              let keys = [];
              keys.push(record.id);
              this.selectedRowKeys = keys;
              this.selectUser = record;
              console.log("this.selectUser", this.selectUser);
            }
          },
        },
      };
    },
    //搜索姓名或账号
    onSearch() {
      this.searchText = this.searchName;
      this.getUser();
    },
    //选择角色
    handleRoleChange(value) {
      console.log(
        "%c [ 选择角色 ]-716",
        "font-size:13px; background:pink; color:#bf2c9f;",
        value
      );
      this.searchLevel = value;
      if (value == "all") {
        this.searchLevel = null;
      }
      this.getUser();
    },
  },
};
</script>

<style scoped lang="less">
@import "~@/assets/css/userList.less";
</style>
